import { WechatferryAgent } from '@wechatferry/agent'


//  ====== ↓↓↓↓↓↓↓↓↓↓↓ 开始配置，根据情况自行配置
const __config = {
  // [配置1]：要监测的群聊名称，不全没问题，可以是名字的前几个字
  wacthList: [
    "航海实战 | 核心志愿者&领队群",
    "测试自动回复"
  ],
  // [配置2]：要监测的消息内容，为了安全起见，一定要完整，比如想要监听"1”，那就输入"1"
  // 具体：配置了监听"1"，来了消息"11"，则不会触发。来了消息"1"，则会触发
  watchMessage: [
    "1",
  ],
  // [配置3]：回复消息
  replayMessage: "1",
}
//  ====== ↑↑↑↑↑↑↑↑↑↑↑ 结束配置，根据情况自行配置


// 创建 agent 实例
const agent = new WechatferryAgent()
let cache = {};
let cacheRoom = {};

// 监听微信消息
agent.on('message', (msg) => {
  const {roomid, content, is_self, is_group} = msg;
  if (!cacheRoom[roomid]) {
    cacheRoom[roomid] = agent.getChatRoomInfo(roomid);
  }
  // 经测试，会有不稳定的情况发生，此处判断一下
  if (cacheRoom[roomid]) {
    try {
      const roomInfo = cacheRoom[roomid];
      const chatRoomName = roomInfo.nickName;
      const {wacthList, watchMessage, replayMessage} = __config;
      const isWatchObj = wacthList.findIndex(name => chatRoomName.startsWith(name)) >= 0;
      const isWatchMsg = watchMessage.indexOf(content) >= 0;
      if (!is_self && is_group && isWatchObj && isWatchMsg) {
        // 判断回复时间间隔
        const diff = 30 * 1000; //间隔30秒
        if (!cache[roomid] || Date.now() - cache[roomid] > diff) {
          console.log("45 ==== 发送消息", replayMessage);
          // 回复消息
          agent.sendText(roomid, replayMessage);
          // 记录回复时间
          cache[roomid] = Date.now();
        }
      }
    } catch (error) {
      
    }
  }
})

// 启动 wcf
agent.start()